<?php


class PostsController extends AppController{
	public $helpers =array('Html','Form');

	public function index(){
		$posts = $this->Post->find('all');
		//var_dump($posts);
		$this->set('posts', $posts);
	}
	
	public function Home(){
		$posts = $this->Post->find('all');
		//var_dump($posts);
		$this->set('posts', $posts);
	}
	
	public function view($id = null){
		if(!$id){
			throw new NotFoundException(__('Invalid Post'));
		}
		$post = $this ->Post->findById($id);
		if(!$post){
			throw new NotFoundException(__('Invalid Post'));
		}
		$this->set('post', $post);
	}
	
	public function inbound(){
 		$drink = $_POST["text"];
 		$url = 'http://sendgrid.com/';
 		$name = $_POST["subject"];
		$user = 'ppoggi92';
		$pass = 'Arbiter0';
		$num_attachments = $_POST["attachments"];
		
		$pictureid = $this->add($name, $drink);

		if ($num_attachments){
			  move_uploaded_file ($_FILES['attachment1']['tmp_name'], WWW_ROOT . '/img/' . $pictureid . '.jpg');
		}
		

		$params = array(
		'api_user'  => $user,
		'api_key'   => $pass,
		'to'        => 'ppoggi92@gmail.com',
		'subject'   => 'testing from barhack',
		'html'      => $testbody,
		'text'      => $testbody,
		'from'      => 'ppoggi92@gmail.com',
  );


$request =  $url.'api/mail.send.json';

// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

// obtain response
$response = curl_exec($session);
curl_close($session);

// print everything out
print_r($response);
 	
 	}

  protected function add($name, $drink) {
        if ($this->request->is('post')) {
            $this->Post->create(array(
            	'title' => $name,
            	'drink' => $drink
            ));

            $this->Post->save();

			return $this->Post->getInsertID();
        }
    }


	public function delete($id) {
		if ($this->request->is('get')) {
			throw new MethodNotAllowedException();
		}

		if ($this->Post->delete($id)) {
			$this->Session->setFlash(
				__('The post with id: %s has been deleted.', h($id))
			);
			return $this->redirect(array('action' => 'index'));
		}
	}
public function isAuthorized($user) {
    // All registered users can add posts
    if ($this->action === 'add') {
        return true;
    }

    // The owner of a post can edit and delete it
    if (in_array($this->action, array('edit', 'delete'))) {
        $postId = $this->request->params['pass'][0];
        if ($this->Post->isOwnedBy($postId, $user['id'])) {
            return true;
        }
    }

    return parent::isAuthorized($user);
}
	
}